﻿using System;
using System.Text;
using System.Web;
using System.Web.UI;
using Besture.Utils;

namespace Besture.UI.Admin.Control
{
    public partial class UploadFile : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/plain";
            Response.Charset = "utf-8";
            var httpPostedFile = Request.Files["ProductPhotoFile"];
            string yearMonthPath = GetYearMonthPath();
            //上传图片路径
            string normalFolder = Request["FolderPath"] + yearMonthPath;
            //检测上传图片路径
            string absoluteNormalFolderPath = DetectionDirectory(normalFolder);
            if (httpPostedFile == null)
            {
                /*失败发送0*/
                Response.Write("0");
                Response.End();
            }
            //图片名称
            string timestamp = string.Empty;
            string photoFileName = GetPhotoFileName(httpPostedFile, ref timestamp);
            //图片路径（用于发至前台）
            string photoFilePath = yearMonthPath +"/" + photoFileName;
            //正常图片路径 
            string normalPhotoFilePath = absoluteNormalFolderPath + photoFileName;
            httpPostedFile.SaveAs(normalPhotoFilePath);
            //文件地址
            Response.Write(string.Format(@"{0}|{1}", photoFilePath, photoFileName));
            Response.End();
        }
        /// <summary>
        /// 获取文件夹路径
        /// </summary>
        /// <returns></returns>
        public string GetFolderPath(string _folderPath)
        {
            return _folderPath + DateTime.Now.ToString("yyyy-MM-dd") + "/";
        }

        /// <summary>
        /// 获取年月文件夹
        /// </summary>
        
        /// <returns></returns>
        public string GetYearMonthPath()
        {
            return DateTime.Now.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 检测目录，如果无则创建
        /// </summary>
        public string DetectionDirectory(string path)
        {
            string absolutePath = Server.MapPath(path);
            if (!System.IO.Directory.Exists(absolutePath))
            {
                System.IO.Directory.CreateDirectory(absolutePath);
            }
            return absolutePath + "\\";
        }

        /// <summary>
        /// 获取图片名称
        /// </summary>
        /// <param name="httpPostedFile"></param>
        /// <returns></returns>
        public string GetPhotoFileName(HttpPostedFile httpPostedFile,ref string timestamp)
        {
            timestamp = Fun.GetTimestamp();
            var strEx = (Fun.GetExName(httpPostedFile.FileName)).ToLower();
            return timestamp + strEx;
        }
    }
}